package com.gec.util;

import java.io.File;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component("emailutil")
public class EmailUtil {

	@Autowired
	@Qualifier("mailSender")
	private JavaMailSender mailSender = null;

	public void sendEmail(String to, String title, String content) {
		// 发送邮件
		SimpleMailMessage m = new SimpleMailMessage();
		m.setTo(to);
		m.setFrom("694386114@qq.com");
		m.setSubject(title);
		m.setText(content);
		mailSender.send(m);
		System.out.println("发送成功!");
	}

	public void sendEmail(String to, String title, String html, String[] filepaths) {
		// 用复杂的格式传输复杂的邮件(带附件,html格式)
		MimeMessage me = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(me, true, "utf-8");
			helper.setTo(to);
			helper.setFrom("694386114@qq.com");
			helper.setSubject(title);
			helper.setText(html, true);

			if (filepaths != null && filepaths.length > 0) {
				for (String path : filepaths) {
					File file = new File(path);
					helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
				}
			}

			mailSender.send(helper.getMimeMessage());
			System.out.println("发送成功!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("发送邮件错误" + e.getMessage(), e);
		}
	}

}
